package parser

import (
	"GraduationProject/public/models"
	"GraduationProject/worker/fengchedm/fengchedm_conf"
	"bytes"
	"encoding/json"
	"regexp"
	"strconv"
)

var (
	titleRegex  = regexp.MustCompile(`<span class="names">([^<]*)</span>`)
	updateRegex = regexp.MustCompile(`<p>更新：([^<]*)</p>`)
	detailRegex = regexp.MustCompile(`<li><a href="([^"]*)" target="_blank">([^<]*)</a></li>`)
)

type FengchedmDetail struct {
	Title  string `json:"title"`
	Update string `json:"update"`
	Detail string `json:"detail"`
}

func Detail(seed models.Record, content []byte) (seeds []models.Record, results []models.Record) {
	var fengchedmDetail FengchedmDetail

	title := titleRegex.FindAllStringSubmatch(string(content), 1)
	update := updateRegex.FindAllStringSubmatch(string(content), 1)
	detail := detailRegex.FindAllStringSubmatch(string(content), -1)

	if len(title) == 1 {
		fengchedmDetail.Title = title[0][1]
	}

	if len(update) == 1 {
		fengchedmDetail.Update = update[0][1]
	}

	detailList := make([]models.Param, 0, len(detail))

	for _, v := range detail {
		detailList = append(detailList, models.Param{
			Key:   v[2],
			Value: fengchedm_conf.Prefix + v[1],
		})
	}

	var str bytes.Buffer
	ddtail, _ := json.Marshal(detailList)
	_ = json.Indent(&str, ddtail, "", "    ")

	fengchedmDetail.Detail = str.String()

	detailBytes, _ := json.Marshal(fengchedmDetail)

	seed.Result = string(detailBytes)
	seed.NotElastic = false
	seed.UniqueKey = strconv.Itoa(int(seed.ID)) + "-" + seed.Url
	results = append(results, seed)
	return
}
